package App.Repository;

import App.Model.BaseEnum;
import App.Model.Chat.CrmChatGroupPart;
import App.Model.Project.*;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * Created by xw on 2019/3/8.
 */
public class ExpireRepository {

/*

    //新增
    @Transactional
    public int insertProject_old(ProjectSaveRequest _request, int userId) throws Exception {

        int result = 0;
        try {

            //添加项目主数据
            String _projectid = UUID.randomUUID().toString();
            String _projectName = _request.getName();
            int _projectType = _request.getProjecttype();
            result = insertProject(_projectid, _projectName, _projectType, userId);

            List<CrmProjectStageName> _stageNameList = getProjectStageName(_projectType);
            List<CrmProjectBasicFolder> _basicFolder = getProjectBasicFolder(_projectType);

            int _commonStageFolderType = BaseEnum.ProjectFolderType.Common.getProjectFolderType();
            List<CrmProjectBasicFolder> _commonStageFolders = _basicFolder.stream().filter(x -> x.getRectype() == _commonStageFolderType).collect(Collectors.toList());

            //服务端产生的folders
            List<ProjectFolderResponse> _serviceProjectFolders = new ArrayList<>();

            //添加项目文件夹
            String _realFolderName = "";
            String _projectFolderId = UUID.randomUUID().toString();

            for (CrmProjectBasicFolder _folder : _commonStageFolders) {
                _realFolderName = _folder.getRecname();
                int _innerFolderType = _folder.getInnerfoldertype();
                boolean _isLawyerFolder = false;
                insertProjectFolderBasic(_projectid, 0, _projectFolderId, _realFolderName, _commonStageFolderType, "", "", _innerFolderType, _isLawyerFolder, userId);

                //把生成的文件夹，放进文件夹池子
                ProjectFolderResponse _theServiceFolder = new ProjectFolderResponse();
                _theServiceFolder.setClientid("");
                _theServiceFolder.setFolderid(_projectFolderId);
                _theServiceFolder.setFoldername(_realFolderName);
                _theServiceFolder.setPartanme(_realFolderName);
                _theServiceFolder.setFoldertype(_folder.getRectype());
                _theServiceFolder.setInnerfoldertype(_folder.getInnerfoldertype());
                _theServiceFolder.setLawyerfolder(false);
                _serviceProjectFolders.add(_theServiceFolder);
            }

            List<ProjectStage> _stages = _request.getStages();
            for (ProjectStage _stage : _stages) {

                int _stageid = _stage.getStageid();
                List<CrmProjectStageName> _currentSageNameList = _stageNameList.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());
                String _currentStageName = _currentSageNameList.get(0).getStagename();

                //虚拟文件夹
                List<ProjectFolderResponse> _folders = _stage.getFolders();

                //服务端产生的阶段
                List<ProjectFolderResponse> _serviceStageFolders = new ArrayList<>();

                //保存项目的阶段
                insertProjectStageRelate(_projectid, _stageid, _stage.getStageorder(), userId);

                // 委托人文件夹
                int _clientStageFolderType = BaseEnum.ProjectFolderType.Client.getProjectFolderType();
                List<CrmProjectBasicFolder> _clientStageFolders = _basicFolder.stream().filter(x -> x.getRectype() == _clientStageFolderType).collect(Collectors.toList());

                //创建分组
                int _chatType = BaseEnum.ChatType.Project.getChatType();
                int _addGroupResult = 0;

                //添加 委托人
                List<ProjectClientGroup> _clientGroups = new ArrayList<>();
                List<ProjectClient> _clients = _stage.getInfo().getClient();
                int _personType = BaseEnum.PersonType.Client.getPersonType();

                List<ProjectClientFolder> _clientTmp = new ArrayList<>();

                for (ProjectClient _client : _clients) {
                    String _clientRecid = UUID.randomUUID().toString();
                    String _clientName = _client.getName();
                    insertProjectClientSingle(_projectid, _stageid, _personType, _clientRecid, _client);

                    ProjectClientFolder _tmpInfo = new ProjectClientFolder();
                    _tmpInfo.setClientid(_client.getClientid());
                    _tmpInfo.setRecid(_clientRecid);
                    _tmpInfo.setClientname(_clientName);
                    _clientTmp.add(_tmpInfo);

                    //添加委托人团队的委托人组的文件夹
                    String _tmpFolderName = "(" + _currentStageName + ")";
                    String _theClientId = _client.getClientid();
                    long _count1 = _folders.stream().filter(x -> x.getFoldertype() == _clientStageFolderType && x.getClientid().equals(_theClientId)).count();
                    if (_count1 == 0) {
                        for (CrmProjectBasicFolder _folder : _clientStageFolders) {
                            _realFolderName = _tmpFolderName + _folder.getRecname();
                            int _innerFolderType = _folder.getInnerfoldertype();
                            boolean _isLawyerFolder = false;
                            insertProjectFolder(_projectid, _stageid, _realFolderName, _clientStageFolderType, _clientRecid, _clientName, _innerFolderType, _isLawyerFolder, userId);
                        }
                    }


                    boolean _createIMGroupResult = false;
                    String _clientGroupid = UUID.randomUUID().toString();

                    //im group name 最长30字节
                    String _groupName = "_委托人协作团队";
                    String _imGroupName = "委托人协作团队";
                    int _clientGroupType = BaseEnum.GroupType.Client.getGroupType();

                    _addGroupResult = insertChatGroup(_clientGroupid, _groupName, _projectid, _stageid, _chatType, _clientGroupType, _clientRecid, _client.getName(), userId);
                    if (_addGroupResult > 0) {
                        _createIMGroupResult = _imService.createIMGroup(_clientGroupid, _imGroupName, userId);
                    }

                    if (_createIMGroupResult) {
                        System.out.println("create im group ok 1");
                    }
                    //添加委托人对应的成员
                    List<ProjectMember> _clientMembers = _client.getMembers();
                    if (_clientMembers != null && _clientMembers.size() > 0) {
                        insertProjectMemberBatch(_projectid, _stageid, _clientGroupid, _clientMembers, _clientRecid, userId);
                        //todo: 添加IM member
                        List<Integer> _tmpMemberIds = new ArrayList<>();
                        for (ProjectMember _m : _clientMembers) {
                            _tmpMemberIds.add(_m.getUserid());
                        }
                        //添加成员到im group
                        //List<Integer> _lawyerGroupMember = _members.stream().map(x -> x.getUserid()).distinct().collect(Collectors.toList());
                        _imService.addIMGroupMember(_clientGroupid, _tmpMemberIds, userId);
                    }

                    //为添加成员做准备
                    ProjectClientGroup _cg = new ProjectClientGroup();
                    _cg.setRecid(_clientRecid);
                    _cg.setClientid(_client.getClientid());
                    _cg.setGroupid(_clientGroupid);
                    _clientGroups.add(_cg);
                }
                System.out.println("ProjectClientGroup:" + _clientGroups.size());

                //添加 对方当事人
                _personType = BaseEnum.PersonType.litigant.getPersonType();
                List<ProjectClient> _litigants = _stage.getInfo().getLitigant();
                int _ligigantStageFolderType = BaseEnum.ProjectFolderType.Litigant.getProjectFolderType();
                List<CrmProjectBasicFolder> _ligigantStageFolders = _basicFolder.stream().filter(x -> x.getRectype() == _ligigantStageFolderType).collect(Collectors.toList());

                for (ProjectClient _client : _litigants) {

                    String _clientRecid = UUID.randomUUID().toString();
                    insertProjectClientSingle(_projectid, _stageid, _personType, _clientRecid, _client);

                    ProjectClientFolder _tmpInfo = new ProjectClientFolder();
                    _tmpInfo.setClientid(_client.getClientid());
                    _tmpInfo.setRecid(_clientRecid);
                    _tmpInfo.setClientname(_client.getName());
                    _clientTmp.add(_tmpInfo);

                    //添加文件夹
                    String _tmpFolderName = "(" + _currentStageName + ")";
                    long _count2 = 0;
                    if (_folders != null) {
                        _count2 = _folders.stream().filter(x -> x.getFoldertype() == _ligigantStageFolderType && x.getClientid().equals(_client.getClientid())).count();
                    }
                    if (_count2 == 0) {
                        for (CrmProjectBasicFolder _folder : _ligigantStageFolders) {
                            _realFolderName = _tmpFolderName + _folder.getRecname();
                            int _innerFolderType = _folder.getInnerfoldertype();
                            boolean _isLawyerFolder = false;
                            insertProjectFolder(_projectid, _stageid, _realFolderName, _ligigantStageFolderType, _clientRecid, _client.getName(), _innerFolderType, _isLawyerFolder, userId);
                        }
                    }
                }

                //添加项目基础数据
                insertProjectInfo(_projectid, _stageid, _stage);

                //添加备注
                List<ProjectRemark> _remarks = _stage.getInfo().getRemarks();
                for (ProjectRemark _remark : _remarks) {

                    String _recid = UUID.randomUUID().toString();
                    insertProjectRemark(_projectid, _stageid, _recid, _remark.getContent(), userId);

                    //添加可以看到备注的人
                    List<ProjectInfoRemarkViewer> _viewers = _remark.getViewer();
                    insertProjectRemarkViewers(_projectid, _stageid, _recid, _viewers, userId);
                }
                //合议庭张三
                int _contactType = BaseEnum.ContactType.FullCount.getContactType();
                List<ProjectContact> _fullCount = _stage.getInfo().getFullcourt();
                insertProjectContact(_projectid, _stageid, _contactType, _fullCount, userId);

                //书记员王五
                _contactType = BaseEnum.ContactType.Clerk.getContactType();
                List<ProjectContact> _clerks = _stage.getInfo().getClerk();
                insertProjectContact(_projectid, _stageid, _contactType, _clerks, userId);

                //阶段的文件夹
                int _stageFolderType = BaseEnum.ProjectFolderType.Stage.getProjectFolderType();
                long _sCount = 0;
                if (_folders != null) {
                    _sCount = _folders.stream().filter(x -> x.getFoldertype() == _stageFolderType).count();
                }
                if (_sCount == 0) {
                    List<CrmProjectBasicFolder> _stageFolder = _basicFolder.stream().filter(x -> x.getRectype() == _stageFolderType).collect(Collectors.toList());
                    if (_stageFolder != null && _stageFolder.size() > 0) {
                        String _folderName = "";
                        String _prefixName = "";
                        for (CrmProjectBasicFolder _folder : _stageFolder) {
                            _folderName = "(" + _currentStageName + ")" + _folder.getRecname();
                            int _innerFolderType = _folder.getInnerfoldertype();
                            boolean _isLawyerFolder = false;
                            if (_folder.getFoldertype() == BaseEnum.DefaultFolderType.LawyerFolder.getDefaultFolderType()) {
                                _isLawyerFolder = true;
                                _prefixName = "律师协作团队";
                            } else {
                                _isLawyerFolder = false;
                                _prefixName = "";
                            }
                            insertProjectFolder(_projectid, _stageid, _folderName, _stageFolderType, "", _prefixName, _innerFolderType, _isLawyerFolder, userId);
                        }
                    }
                }

                //添加文件
                List<ProjectFile> _files = new ArrayList<>();
                List<ProjectFileFolder> _fileFolders = _stage.getFiles();
                for (ProjectFileFolder _folder : _fileFolders) {
                    List<ProjectFile> _items = _folder.getItems();
                    for (ProjectFile _file : _items) {
                        _file.setFolderid(_folder.getFolderid());
                        _file.setFoldername(_folder.getFoldername());
                        _files.add(_file);
                    }
                }

                //把文件夹写入数据库
                List<ProjectFolderResponse> _projectFolders = _folders.stream().filter(x -> x.getFoldertype() == _commonStageFolderType).collect(Collectors.toList());
                String _tmpId = "";
                if (_projectFolders != null && _projectFolders.size() > 0) {
                    _tmpId = _projectFolders.get(0).getFolderid();
                }
                for (ProjectFile _f : _files) {
                    String _recid = UUID.randomUUID().toString();

                    //如果是项目文件夹，就修改一下文件夹id
                    //为了处理每请求一次一次文件夹api，但是项目文件夹id不同的问题
                    //替换客户端的folderid 为 服务端产生的 folderid
                    if (_f.getFolderid().equals(_tmpId)) {
                        _f.setFolderid(_projectFolderId);
                    }
                    insertProjectFileBasic(_projectid, _stageid, _recid, _f, userId);
                }


                //添加项目任务
                List<ProjectTask> _tasks = _stage.getTasks();
                if (_tasks != null) {
                    insertProjectTasks(_projectid, _stageid, _tasks, userId);
                }

                //添加律师协作团队聊天组
                boolean _createIMGroupResult = false;
                int _clientGroupType = BaseEnum.GroupType.Client.getGroupType();
                String _clientGroupid = UUID.randomUUID().toString();

                _addGroupResult = 0;
                String _lawyerGroupid = UUID.randomUUID().toString();
                //String _groupName = _projectName + "律师协作团队";
                String _groupName = "律师协作团队";
                String _imGroupName = "律师协作团队";
                int _lawyerGroupType = BaseEnum.GroupType.Lawyer.getGroupType();
                _addGroupResult = insertChatGroup(_lawyerGroupid, _groupName, _projectid, _stageid, _chatType, _lawyerGroupType, "", "", userId);
                if (_addGroupResult > 0) {
                    _createIMGroupResult = _imService.createIMGroup(_lawyerGroupid, _imGroupName, userId);
                }
                if (_createIMGroupResult) {
                    System.out.println("create im group ok 2");
                }

                //添加律师协作团队成员
                List<ProjectMember> _members = _stage.getMembers();
                insertProjectMember(_projectid, _stageid, _lawyerGroupid, _members, userId);

                //添加成员到im group
                List<Integer> _lawyerGroupMember = _members.stream().map(x -> x.getUserid()).distinct().collect(Collectors.toList());
                _imService.addIMGroupMember(_lawyerGroupid, _lawyerGroupMember, userId);

                //文件夹
                //如何拿到新增的client的id
                for (ProjectFolderResponse _f : _folders) {

                    //判断委托人是否已经删除了
                    if (_f.getFoldertype() == _clientStageFolderType) {
                        long _c1 = _clients.stream().filter(x -> x.getClientid().equals(_f.getClientid())).count();
                        if (_c1 == 0) {
                            continue;
                        }
                    }

                    if (_f.getFoldertype() == _ligigantStageFolderType) {
                        long _c2 = _litigants.stream().filter(x -> x.getClientid().equals(_f.getClientid())).count();
                        if (_c2 == 0) {
                            continue;
                        }
                    }

                    String _finalFolderName = "";
                    if (_f.getFoldertype() == BaseEnum.ProjectFolderType.UserDefine.getProjectFolderType()) {
                        _finalFolderName = _f.getFoldername();
                    } else {
                        if (_f.getPartanme() == null || _f.getPartanme().isEmpty()) {

                            String[] _segments = _f.getFoldername().split("\\(");
                            if (_segments != null && _segments.length > 1) {
                                _finalFolderName = "(" + _segments[1];
                            } else {
                                _finalFolderName = "";
                            }
                        } else {
                            _finalFolderName = _f.getPartanme();
                        }
                    }

                    //委托人，对方当事人 文件夹
                    int _innerFolderType = _f.getInnerfoldertype();
                    List<ProjectClientFolder> _tmp = _clientTmp.stream().filter(x -> x.getClientid().equals(_f.getClientid())).collect(Collectors.toList());
                    if (_tmp != null && _tmp.size() > 0) {
                        ProjectClientFolder _t = _tmp.get(0);
                        String _recid = _t.getRecid();
                        String _name = _t.getClientname();
                        boolean _isLawyerFolder = false;
                        insertProjectFolderBasic(_projectid, _stageid, _f.getFolderid(), _finalFolderName, _f.getFoldertype(), _recid, _name, _innerFolderType, _isLawyerFolder, userId);
                    } else {
                        //项目文件加，阶段文件夹
                        if (_f.getFoldertype() == _commonStageFolderType) {
                            continue;
                        }
                        boolean _isLawyerFolder = _f.isLawyerfolder();
                        String _prefixName = "";
                        if (_isLawyerFolder) {
                            _prefixName = "律师协作团队_2";
                        } else {
                            _prefixName = "";
                        }
                        insertProjectFolderBasic(_projectid, _stageid, _f.getFolderid(), _finalFolderName, _f.getFoldertype(), "", _prefixName, _innerFolderType, _isLawyerFolder, userId);
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return result;
    }


    @Transactional
    public int updateProject_old(ProjectSaveRequest _request, int userId) throws Exception {
        int result = 0;
        try {

            String _projectid = _request.getProjectid();
            int _projectType = _request.getProjecttype();

            //更新项目主数据
            result = updateProjectMain(_projectid, _request.getName());

            List<CrmProjectClient> _oldProjectClient = getProjectClient(_projectid);

            //对方委托人
            List<CrmProjectClient> _allProjectClinet = _oldProjectClient.stream().filter(x -> x.getPersontype() == BaseEnum.PersonType.Client.getPersonType()).collect(Collectors.toList());

            //对方当事人
            List<CrmProjectClient> _allLitigantList = _oldProjectClient.stream().filter(x -> x.getPersontype() == BaseEnum.PersonType.litigant.getPersonType()).collect(Collectors.toList());

            //获取 stage relate
            List<CrmProjectStageRelate> _oldStageRelates = getProjectStageRelate(_projectid);

            //删除old  stage relate
            deleteProjectStageRelate(_oldStageRelates);

            //项目基本数据
            List<CrmProjectInfo> _projectInfos = getProjectInfo(_projectid);

            //读取合议庭和数据源
            List<CrmProjectContact> _projectContactList = getProjectContact(_projectid, userId);

            //删除合议庭和数据源
            deleteProjectContact(_projectContactList);

            //获取备注
            List<CrmProjectRemark> _remarks = getProjectRemark(_projectid, userId);

            //获取可以看到备注的人
            List<CrmProjectInfoRemarkViewer> _viewers = getProjectRemarkViewer(_projectid, userId);

            //读取老文件
            List<CrmProjectFile> _projectFileList = getProjectFiles(_projectid, userId);

            //删除老文件
            deleteProjectFiles(_projectFileList, userId);

            //删除老的任务
            List<CrmProjectTask> _tasks = getProjectTask(_projectid);
            deleteProjectTasks(_tasks);

            //获取项目成员
            List<CrmProjectMember> _memberList = getProjectMember(_projectid, userId);

            //需要添加的基本文件夹
            List<CrmProjectBasicFolder> _basicFolder = getProjectBasicFolder(_projectType);
            int _commonStageFolderType = BaseEnum.ProjectFolderType.Common.getProjectFolderType();
            List<CrmProjectBasicFolder> _commonStageFolders = _basicFolder.stream().filter(x -> x.getRectype() == _commonStageFolderType).collect(Collectors.toList());

            // 委托人的基本文件夹
            int _stageFolderType = BaseEnum.ProjectFolderType.Stage.getProjectFolderType();
            int _clientStageFolderType = BaseEnum.ProjectFolderType.Client.getProjectFolderType();
            int _litigantFolderType = BaseEnum.ProjectFolderType.Litigant.getProjectFolderType();

            List<CrmProjectBasicFolder> _clientStageFolders = _basicFolder.stream().filter(x -> x.getRectype() == _clientStageFolderType).collect(Collectors.toList());
            List<CrmProjectBasicFolder> _litigantStageFolders = _basicFolder.stream().filter(x -> x.getRectype() == _litigantFolderType).collect(Collectors.toList());

            List<ProjectStage> _stages = _request.getStages();

            //获取项目的文件夹
            List<CrmProjectFolder> _folders = getProjectFolder(_projectid, userId);
            //删除已经移除的阶段文件夹
            List<CrmProjectFolder> _oldFolders = _folders.stream().filter(x -> x.getFoldertype() == _stageFolderType).collect(Collectors.toList());
            //删除已经移除了的阶段文件夹
            for (CrmProjectFolder _f : _oldFolders) {
                List<ProjectStage> _tmp = _stages.stream().filter(x -> x.getStageid() == _f.getStageid()).collect(Collectors.toList());
                if (_tmp == null || _tmp.size() == 0) {
                    deleteProjectFolder(_f.getRecid(), userId);
                }
            }

            //获取项目的聊天分组
            List<CrmChatGroupPart> _chatGroups = getProjectChatGroup(_projectid);
            List<CrmProjectStageName> _stageNameList = getProjectStageName(_projectType);

            // int _stageid = 0;
            for (ProjectStage _stage : _stages) {
                int _stageid = _stage.getStageid();
                List<CrmProjectStageName> _currentSageNameList = _stageNameList.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());
                String _stageName = _currentSageNameList.get(0).getStagename();

                //当前阶段的成员
                List<CrmProjectMember> _stageMembers = _memberList.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());

                //循环之外已经删除了old stage relate s数据，这里只需要新增
                insertProjectStageRelate(_projectid, _stageid, _stage.getStageorder(), userId);

                //文件夹
                //如果新加了阶段，就新增文件夹，
                List<ProjectFolderResponse> _tmpStageFolders = _stage.getFolders();
                List<CrmProjectFolder> _tmpStagefolders = _folders.stream().filter(x -> x.getStageid() == _stageid && x.getFoldertype() == _stageFolderType).collect(Collectors.toList());
                if (_tmpStagefolders == null || _tmpStagefolders.size() == 0) {

                    //新增阶段文件夹
                    List<ProjectFolderResponse> _stageFolders = _tmpStageFolders.stream().filter(x -> x.getFoldertype() == _stageFolderType).collect(Collectors.toList());
                    List<CrmProjectBasicFolder> _baseStageFolders = _basicFolder.stream().filter(x -> x.getRectype() == _stageFolderType).collect(Collectors.toList());
                    if (_baseStageFolders != null && _baseStageFolders.size() > 0) {
                        String _folderName = "";
                        String _currentFolderId = "";

                        //从前段数据中找文件夹id
                        for (CrmProjectBasicFolder _folder : _baseStageFolders) {
                            if (_stageFolders != null && _stageFolders.size() > 0) {
                                _currentFolderId = _stageFolders.get(0).getFolderid();
                            } else {
                                _currentFolderId = UUID.randomUUID().toString();
                            }

                            _folderName = "(" + _stageName + ")" + _folder.getRecname();
                            int _innerFolderType = _folder.getInnerfoldertype();
                            boolean _isLawyerFolder = false;
                            if (_folder.getFoldertype() == BaseEnum.DefaultFolderType.LawyerFolder.getDefaultFolderType()) {
                                _isLawyerFolder = true;
                            }
                            insertProjectFolderBasic(_projectid, _stageid, _currentFolderId, _folderName, _stageFolderType, "", "", _innerFolderType, _isLawyerFolder, userId);
                        }
                    }
                }


                //委托人的更新,删除,新增操作
                List<ProjectClientGroup> _clientGroups = new ArrayList<>();
                int _personType = BaseEnum.PersonType.Client.getPersonType();
                List<ProjectClient> _clients = _stage.getInfo().getClient();
                List<CrmProjectClient> _savedClients = _allProjectClinet.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());
                if (_clients == null || _clients.size() == 0) {
                    //删除委托人
                    deleteProjectClientBatch(_savedClients);
                    //删除委托人的聊天组
                    for (CrmProjectClient _c : _savedClients) {
                        List<CrmChatGroupPart> _tmpChatGroups = _chatGroups.stream().filter(x -> x.getStageid() == _stageid
                                && x.getRelatedid() != null
                                && x.getRelatedid().equals(_c.getRecid())).collect(Collectors.toList());

                        if (_tmpChatGroups != null && _tmpChatGroups.size() > 0) {
                            deleteProjectChatGroupBatch(_tmpChatGroups, userId);
                        }
                    }

                    //删除委托人的文件夹
                    List<CrmProjectFolder> _tmpClientFolders = _folders.stream().filter(x -> x.getStageid() == _stageid && x.getFoldertype() == _clientStageFolderType).collect(Collectors.toList());
                    deleteProjectFolderBatch(_tmpClientFolders, userId);

                    //删除委托人对应的成员
                    List<CrmProjectMember> _oldStageMembers = _stageMembers.stream().filter(x -> x.getRelatedid() != null
                            && x.getGrouptype() == BaseEnum.GroupType.Client.getGroupType()).collect(Collectors.toList());
                    deleteProjectMember(_oldStageMembers, userId);

                } else {
                    //如果没有老数据，就直接新增
                    if (_savedClients == null || _savedClients.size() == 0) {

                        for (ProjectClient _c : _clients) {

                            //新增委托人
                            String _clinetRecid = UUID.randomUUID().toString();
                            insertProjectClientSingle(_projectid, _stageid, _personType, _clinetRecid, _c);

                            //新增文件夹
                            String _tmpFolderName = "(" + _stageName + ")";

                            List<ProjectFolderResponse> _clientTmpFolders = _tmpStageFolders.stream().filter(x -> x.getClientid().equals(_c.getClientid())).collect(Collectors.toList());
                            if (_clientTmpFolders == null || _clientTmpFolders.size() == 0) {
                                insertProjectFolderForClient(_projectid, _stageid, _tmpFolderName, _clientStageFolderType, _clientStageFolders, _clinetRecid, _c.getName(), userId);
                            } else {
                                for (ProjectFolderResponse _f : _clientTmpFolders) {
                                    String _currentFolderid = _f.getFolderid();
                                    String _currentFolderName = _f.getPartanme();
                                    int _innerFolderType = _f.getInnerfoldertype();
                                    boolean _isLawyerFolder = false;
                                    insertProjectFolderBasic(_projectid, _stageid, _currentFolderid, _currentFolderName, _clientStageFolderType, _clinetRecid, _c.getName(), _innerFolderType, _isLawyerFolder, userId);
                                }
                            }

                            //新增聊天分组
                            int _chatType = BaseEnum.ChatType.Project.getChatType();
                            int _addGroupResult = 0;
                            String _clientGroupid = UUID.randomUUID().toString();
                            //im group name 最长30字节
                            String _groupName = "委托人协作团队";
                            String _imGroupName = "委托人协作团队";
                            int _clientGroupType = BaseEnum.GroupType.Client.getGroupType();
                            _addGroupResult = insertChatGroup(_clientGroupid, _groupName, _projectid, _stageid, _chatType, _clientGroupType, _clinetRecid, _c.getName(), userId);
                            if (_addGroupResult > 0) {
                                _imService.createIMGroup(_clientGroupid, _imGroupName, userId);
                            }

                            //添加委托人对应的成员
                            insertProjectMemberBatch(_projectid, _stageid, _clientGroupid, _c.getMembers(), _clinetRecid, userId);
                            //todo:添加成员的到IM

                            ProjectClientGroup _tmpClientGroup = new ProjectClientGroup();
                            _tmpClientGroup.setClientid(_c.getClientid());
                            _tmpClientGroup.setGroupid(_clientGroupid);
                            //_tmpClientGroup.setRecid();
                            _clientGroups.add(_tmpClientGroup);
                        }
                    } else {

                        //更新
                        List<ProjectClient> _oldClients = _clients.stream().filter(x -> x.getRecid() != null && !x.getRecid().isEmpty()).collect(Collectors.toList());
                        updateProjectClient(_oldClients);
                        for (ProjectClient _c : _oldClients) {

                            //更新聊天组名称
                            List<CrmChatGroupPart> _tmpGroups = _chatGroups.stream().filter(x -> x.getRelatedid() != null && x.getRelatedid().equals(_c.getRecid())).collect(Collectors.toList());
                            updateProjectChatGroupNameBatch(_tmpGroups, _c.getName(), userId);

                            //更新文件夹名称
                            List<CrmProjectFolder> _tmpFolders = _folders.stream().filter(x -> x.getStageid() == _stageid
                                    && x.getRelatedid() != null
                                    && x.getRelatedid().equals(_c.getRecid())).collect(Collectors.toList());
                            updateProjectFolderNameBatch(_tmpFolders, _c.getName(), userId);

                            //新增，更新，删除 委托人对应的成员
                            List<ProjectMember> _oldMembers = _c.getMembers().stream().filter(x -> x.getRecid() != null && !x.getRecid().isEmpty()).collect(Collectors.toList());
                            List<ProjectMember> _newMembers = _c.getMembers().stream().filter(x -> x.getRecid() == null || x.getRecid().isEmpty()).collect(Collectors.toList());
                            List<CrmProjectMember> _savedMembers = _stageMembers.stream().filter(x -> x.getRelatedid() != null && x.getRelatedid().equals(_c.getRecid())).collect(Collectors.toList());

                            //新增
                            String _memberGroupId = "";
                            if (_savedMembers != null && _savedMembers.size() > 0) {
                                _memberGroupId = _savedMembers.get(0).getGroupid();
                            } else {

                                //新增聊天分组
                                int _chatType = BaseEnum.ChatType.Project.getChatType();
                                int _addGroupResult = 0;
                                _memberGroupId = UUID.randomUUID().toString();
                                //im group name 最长30字节
                                String _groupName = "委托人协作团队";
                                String _imGroupName = "委托人协作团队";
                                int _clientGroupType = BaseEnum.GroupType.Client.getGroupType();
                                _addGroupResult = insertChatGroup(_memberGroupId, _groupName, _projectid, _stageid, _chatType, _clientGroupType, _c.getRecid(), _c.getName(), userId);
                                if (_addGroupResult > 0) {
                                    _imService.createIMGroup(_memberGroupId, _imGroupName, userId);
                                }
                            }
                            insertProjectMemberBatch(_projectid, _stageid, _memberGroupId, _newMembers, _c.getRecid(), userId);

                            //更新和委托人关联的members
                            if (_oldMembers != null && _oldMembers.size() > 0) {
                                updateProjectMemberBatch(_oldMembers, userId);
                            }
                        }


                        //删除
                        for (CrmProjectClient _c : _savedClients) {
                            List<ProjectClient> _tmp = _oldClients.stream().filter(x -> x.getRecid().equals(_c.getRecid())).collect(Collectors.toList());
                            if (_tmp == null || _tmp.size() == 0) {
                                deleteProjectClient(_c.getRecid());

                                //删除文件夹
                                int _clientFolderType = BaseEnum.ProjectFolderType.Client.getProjectFolderType();
                                List<CrmProjectFolder> _tmpFolders = _folders.stream()
                                        .filter(x -> x.getStageid() == _stageid
                                                && x.getFoldertype() == _clientFolderType
                                                && x.getRelatedid() != null
                                                && x.getRelatedid().equals(_c.getRecid()))
                                        .collect(Collectors.toList());

                                deleteProjectFolderBatch(_tmpFolders, userId);

                                //删除聊天分组
                                List<CrmChatGroupPart> _tmpChatGroups = _chatGroups.stream().filter(x -> x.getStageid() == _stageid
                                        && x.getRelatedid() != null
                                        && x.getRelatedid().equals(_c.getRecid())).collect(Collectors.toList());

                                deleteProjectChatGroupBatch(_tmpChatGroups, userId);


                                //删除委托人对应的成员
                                List<CrmProjectMember> _tmpClientMembers = _stageMembers.stream().filter(x -> x.getRelatedid() != null
                                        && x.getRelatedid().equals(_c.getRecid())).collect(Collectors.toList());

                                // deleteProjectMember(session, _tmpClientMembers, userId);

                            }
                        }

                        //新增
                        List<ProjectClient> _newClients = _clients.stream().filter(x -> x.getRecid() == null || x.getRecid().equals("")).collect(Collectors.toList());
                        //insertProjectClient(session, _projectid, _stageid, _personType, _newClients);
                        for (ProjectClient _c : _newClients) {

                            //新增委托人
                            String _clinetRecid = UUID.randomUUID().toString();
                            insertProjectClientSingle(_projectid, _stageid, _personType, _clinetRecid, _c);

                            //新增文件夹
                            String _tmpFolderName = "(" + _stageName + ")";
                            //insertProjectFolderForClient(session, _projectid, _stageid, _tmpFolderName, _clientStageFolderType, _clientStageFolders, _clinetRecid, _c.getName(), userId);
                            List<ProjectFolderResponse> _clientTmpFolders = _tmpStageFolders.stream().filter(x -> x.getClientid().equals(_c.getClientid())).collect(Collectors.toList());
                            if (_clientTmpFolders == null || _clientTmpFolders.size() == 0) {
                                insertProjectFolderForClient(_projectid, _stageid, _tmpFolderName, _clientStageFolderType, _clientStageFolders, _clinetRecid, _c.getName(), userId);
                            } else {
                                for (ProjectFolderResponse _f : _clientTmpFolders) {
                                    String _currentFolderid = _f.getFolderid();
                                    String _currentFolderName = _f.getPartanme();
                                    int _innerFolderType = _f.getInnerfoldertype();
                                    boolean _isLawyerFolder = false;
                                    insertProjectFolderBasic(_projectid, _stageid, _currentFolderid, _currentFolderName, _clientStageFolderType, _clinetRecid, _c.getName(), _innerFolderType, _isLawyerFolder, userId);
                                }
                            }

                            //新增聊天分组
                            int _chatType = BaseEnum.ChatType.Project.getChatType();
                            int _addGroupResult = 0;
                            String _clientGroupid = UUID.randomUUID().toString();
                            //im group name 最长30字节
                            String _groupName = "_委托人协作团队";
                            String _imGroupName = "委托人协作团队";
                            int _clientGroupType = BaseEnum.GroupType.Client.getGroupType();
                            _addGroupResult = insertChatGroup(_clientGroupid, _groupName, _projectid, _stageid, _chatType, _clientGroupType, _clinetRecid, _c.getName(), userId);
                            if (_addGroupResult > 0) {
                                _imService.createIMGroup(_clientGroupid, _imGroupName, userId);
                            }

                            //添加委托人对应的成员
                            insertProjectMemberBatch(_projectid, _stageid, _clientGroupid, _c.getMembers(), _clinetRecid, userId);

                            ProjectClientGroup _tmpClientGroup = new ProjectClientGroup();
                            _tmpClientGroup.setClientid(_c.getClientid());
                            _tmpClientGroup.setGroupid(_clientGroupid);
                            _clientGroups.add(_tmpClientGroup);

                        }

                    }
                }

                //添加 对方当事人
                List<ProjectClient> _litigants = _stage.getInfo().getLitigant();
                _personType = BaseEnum.PersonType.litigant.getPersonType();
                List<CrmProjectClient> _savedLitigants = _allLitigantList.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());
                if (_litigants == null || _litigants.size() == 0) {

                    //删除委托人
                    deleteProjectClientBatch(_savedLitigants);

                    //删除委托人的文件夹
                    List<CrmProjectFolder> _tmpLitigantFolders = _folders.stream().filter(x -> x.getStageid() == _stageid && x.getFoldertype() == _litigantFolderType).collect(Collectors.toList());
                    deleteProjectFolderBatch(_tmpLitigantFolders, userId);

                } else {
                    if (_savedLitigants == null || _savedLitigants.size() == 0) {
                        for (ProjectClient _c : _litigants) {
                            //新增对方当事人
                            String _litigantRecid = UUID.randomUUID().toString();
                            insertProjectClientSingle(_projectid, _stageid, _personType, _litigantRecid, _c);

                            //新增对方当事人文件夹
                            String _tmpFolderName = "(" + _stageName + ")";
                            List<ProjectFolderResponse> _clientTmpFolders = _tmpStageFolders.stream().filter(x -> x.getClientid().equals(_c.getClientid())).collect(Collectors.toList());
                            if (_clientTmpFolders == null || _clientTmpFolders.size() == 0) {
                                insertProjectFolderForClient(_projectid, _stageid, _tmpFolderName, _litigantFolderType, _litigantStageFolders, _litigantRecid, _c.getName(), userId);
                            } else {
                                for (ProjectFolderResponse _f : _clientTmpFolders) {
                                    String _currentFolderid = _f.getFolderid();
                                    String _currentFolderName = _f.getPartanme();
                                    int _innerFolderType = _f.getInnerfoldertype();
                                    boolean _isLawyerFolder = false;
                                    insertProjectFolderBasic(_projectid, _stageid, _currentFolderid, _currentFolderName, _litigantFolderType, _litigantRecid, _c.getName(), _innerFolderType, _isLawyerFolder, userId);
                                }
                            }
                        }
                    } else {

                        //删除去掉的
                        List<ProjectClient> _oldLitigantList = _litigants.stream().filter(x -> x.getRecid() != null && !x.getRecid().isEmpty()).collect(Collectors.toList());
                        for (CrmProjectClient _c : _savedLitigants) {
                            List<ProjectClient> _tmp = _oldLitigantList.stream().filter(x -> x.getRecid().equals(_c.getRecid())).collect(Collectors.toList());
                            if (_tmp == null || _tmp.size() == 0) {
                                //删除对方当事人
                                deleteProjectClient(_c.getRecid());
                                //删除文件夹
                                List<CrmProjectFolder> _tmpfolders = _folders
                                        .stream()
                                        .filter(x -> x.getStageid() == _stageid && x.getFoldertype() == _litigantFolderType
                                                && x.getRelatedid() != null
                                                && x.getRelatedid().equals(_c.getRecid())).collect(Collectors.toList());

                                if (_tmpfolders != null && _tmpfolders.size() > 0) {
                                    deleteProjectFolderBatch(_tmpfolders, userId);
                                }
                            }
                        }
                        //更新老的
                        updateProjectClient(_oldLitigantList);
                        //更新文件夹名称
                        for (ProjectClient _c : _oldLitigantList) {
                            List<CrmProjectFolder> _tmpFolders = _folders.stream().filter(x -> x.getStageid() == _stageid
                                    && x.getRelatedid() != null
                                    && x.getRelatedid().equals(_c.getRecid())).collect(Collectors.toList());

                            updateProjectFolderNameBatch(_tmpFolders, _c.getName(), userId);
                        }

                        List<ProjectClient> _newLitigantList = _litigants.stream().filter(x -> x.getRecid() == null || x.getRecid().isEmpty()).collect(Collectors.toList());
                        //添加新的
                        if (_newLitigantList != null && _newLitigantList.size() > 0) {
                            for (ProjectClient _c : _newLitigantList) {
                                //新增对方当事人
                                String _litigantRecid = UUID.randomUUID().toString();
                                insertProjectClientSingle(_projectid, _stageid, _personType, _litigantRecid, _c);

                                //新增文件夹
                                String _tmpFolderName = "(" + _stageName + ")";
                                List<ProjectFolderResponse> _clientTmpFolders = _tmpStageFolders.stream().filter(x -> x.getFoldertype() == _litigantFolderType && x.getClientid().equals(_c.getClientid())).collect(Collectors.toList());
                                if (_clientTmpFolders == null || _clientTmpFolders.size() == 0) {

                                    insertProjectFolderForClient(_projectid, _stageid, _tmpFolderName, _litigantFolderType, _litigantStageFolders, _litigantRecid, _c.getName(), userId);
                                } else {
                                    for (ProjectFolderResponse _f : _clientTmpFolders) {
                                        String _currentFolderid = _f.getFolderid();
                                        String _currentFolderName = _f.getPartanme();
                                        int _innerFolderType = _f.getInnerfoldertype();
                                        boolean _isLawyerFolder = false;
                                        insertProjectFolderBasic(_projectid, _stageid, _currentFolderid, _currentFolderName, _litigantFolderType, _litigantRecid, _c.getName(), _innerFolderType, _isLawyerFolder, userId);
                                    }
                                }
                            }
                        }
                        System.out.println("step r12");
                    }
                }

                //获取项目基本信息
                boolean _hasInfo = false;
                CrmProjectInfo _currentInfo = new CrmProjectInfo();
                for (CrmProjectInfo _info : _projectInfos) {
                    if (_info.getStageid() == _stageid) {
                        _currentInfo = _info;
                        _hasInfo = true;
                        break;
                    }
                }

                if (_hasInfo) {
                    //更新基本信息
                    updateProjectInfo(_stage, _currentInfo.getRecid());
                } else {
                    insertProjectInfo(_projectid, _stage, userId);
                }

                //新增合议庭和数据源
                //新增合议庭
                int _contactType = BaseEnum.ContactType.FullCount.getContactType();
                List<ProjectContact> _fullCount = _stage.getInfo().getFullcourt();
                insertProjectContact(_projectid, _stageid, _contactType, _fullCount, userId);

                //新增书记员
                _contactType = BaseEnum.ContactType.Clerk.getContactType();
                List<ProjectContact> _clerks = _stage.getInfo().getClerk();
                insertProjectContact(_projectid, _stageid, _contactType, _clerks, userId);


                //编辑备注和可以看到备注的人
                List<ProjectRemark> _newRemarks = _stage.getInfo().getRemarks();
                List<ProjectRemark> _myNewRemarks = new ArrayList<>();
                if (_newRemarks != null && _newRemarks.size() > 0) {
                    _myNewRemarks = _newRemarks.stream().filter(x -> x.getCreatorid() == userId).collect(Collectors.toList());
                }

                List<CrmProjectInfoRemarkViewer> _currentOldViewer = new ArrayList<>();
                if (_viewers != null && _viewers.size() > 0) {
                    _currentOldViewer = _viewers.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());
                }

                //更新或者新增，自己的备注
                if (_myNewRemarks != null && _myNewRemarks.size() > 0) {

                    for (ProjectRemark _remark : _myNewRemarks) {
                        String _tempRemarkid = _remark.getRecid();
                        String _remarkid = UUID.randomUUID().toString();
                        if (_tempRemarkid == null || _tempRemarkid.equals("")) {
                            //insert
                            insertProjectRemark(_projectid, _stageid, _remarkid, _remark.getContent(), userId);
                            List<ProjectInfoRemarkViewer> _viewList = _remark.getViewer();
                            if (_viewList != null && _viewList.size() > 0) {
                                insertProjectRemarkViewers(_projectid, _stageid, _remarkid, _viewList, userId);
                            }
                        } else {

                            //update
                            updateProjectRemark(_remark.getRecid(), _remark.getContent(), userId);

                            List<ProjectInfoRemarkViewer> _viewList = _remark.getViewer();
                            //old data
                            List<CrmProjectInfoRemarkViewer> _currentOldRemarkViewer = new ArrayList<>();
                            if (_currentOldViewer != null && _currentOldViewer.size() > 0) {
                                _currentOldRemarkViewer = _currentOldViewer.stream().filter(x -> x.getRemarkid().equals(_remark.getRecid())).collect(Collectors.toList());
                            }


                            if (_viewList != null && _viewList.size() > 0) {
                                for (ProjectInfoRemarkViewer _v : _viewList) {
                                    if (_v.getRecid() == null || _v.getRecid().equals("")) {
                                        insertProjectRemarkViewer(_projectid, _stageid, _remark.getRecid(), _v.getUserid(), userId);
                                    }
                                }
                                for (CrmProjectInfoRemarkViewer _v2 : _currentOldRemarkViewer) {
                                    List<ProjectInfoRemarkViewer> _tmp2 = _viewList.stream().filter(x -> x.getRecid() != null && x.getRecid().equals(_v2.getRecid())).collect(Collectors.toList());
                                    if (_tmp2 == null || _tmp2.size() == 0) {
                                        deleteProjectRemarkViewer(_v2.getRecid());
                                    }
                                }
                            } else {
                                if (_currentOldRemarkViewer != null && _currentOldRemarkViewer.size() > 0) {
                                    deleteProjectRemarkViewers(_currentOldRemarkViewer);
                                }
                            }
                        }
                    }

                    //delete old remark
                    if (_remarks != null && _remarks.size() > 0) {
                        List<CrmProjectRemark> _tmpRemarks = _remarks.stream().filter(x -> x.getStageid() == _stageid && x.getReccreator() == userId).collect(Collectors.toList());
                        if (_tmpRemarks != null && _tmpRemarks.size() > 0) {

                            for (CrmProjectRemark _r : _tmpRemarks) {
                                List<ProjectRemark> _tmpRemark = _myNewRemarks.stream().filter(x -> x.getRecid() != null && x.getRecid().equals(_r.getRecid())).collect(Collectors.toList());
                                if (_tmpRemark == null || _tmpRemark.size() == 0) {
                                    deleteProjectRemark(_r.getRecid(), userId);
                                }
                            }
                        }
                    }

                } else {
                    if (_remarks != null && _remarks.size() > 0) {
                        List<CrmProjectRemark> _tmpRemarks = _remarks.stream().filter(x -> x.getStageid() == _stageid && x.getReccreator() == userId).collect(Collectors.toList());
                        if (_tmpRemarks != null && _tmpRemarks.size() > 0) {
                            deleteProjectRemarks(_tmpRemarks, userId);
                        }
                    }
                }


                //新增文件
                List<ProjectFile> _files = new ArrayList<>();
                List<ProjectFileFolder> _fileFolders = _stage.getFiles();
                for (ProjectFileFolder _folder : _fileFolders) {
                    List<ProjectFile> _items = _folder.getItems();
                    for (ProjectFile _file : _items) {
                        _file.setFolderid(_folder.getFolderid());
                        _file.setFoldername(_folder.getFoldername());
                        _files.add(_file);
                    }
                }

                //老文件删除了，重新添加一遍
                //不应该这样，把原始上传时间，上传人给去掉了
                //如果有fileid就是老数据
                insertProjectFile(_projectid, _stageid, _files, userId);

                //更新文件的名字
                //todo:更新应该没有效果，没有id
                for (ProjectFile _f : _files) {
                    updateProjectFile(_f);
                }

                //新增项目任务
                List<ProjectTask> _taskList = _stage.getTasks();
                insertProjectTasks(_projectid, _stageid, _taskList, userId);

                //编辑项目成员
                List<ProjectMember> _membersRequest = _stage.getMembers();
                List<ProjectMember> _savedMembers = _membersRequest.stream().filter(x -> x.getRecid() != null && !x.getRecid().isEmpty()).collect(Collectors.toList());
                if (_savedMembers != null && _savedMembers.size() > 0) {
                    updateProjectMemberBatch(_savedMembers, userId);
                }

                //编辑律师协作团队成员
                int _lawyerGroupType = BaseEnum.GroupType.Lawyer.getGroupType();
                List<CrmProjectMember> _laywerMemberList = _memberList.stream().filter(x -> x.getGrouptype() == _lawyerGroupType).collect(Collectors.toList());
                projectMemmberEdit(_projectid, _stageid, _membersRequest, _laywerMemberList, userId);


            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return result;
    }
*/

}
